import requests
import json


class Gitee():
    def __init__(self, os_name, access_token, owner, sort, direction):
        self.os_name = os_name
        self.access_token = access_token
        self.owner = owner
        self.sort = sort
        self.direction = direction

    def search_branch(self, target):
        url = f"https://gitee.com/api/v5/repos/{self.owner}/{target}/branches"
        params = {
            'access_token': self.access_token,
            'owner': self.owner,
            'repo': target,
            'sort': self.sort,
            'direction': self.direction,
            'page': 1,
            'per_page': 100,
        }

        r = requests.get(url, params=params)
        if not r.status_code == 200:
            return

        # 整理结果
        for branch in json.loads(r.text):
            branch_url = f"https://gitee.com/{self.owner}/{target}/tree/{branch['name']}/"
            yield branch['name'], self.owner, 'gitee', f"{target}: {branch['name']}", branch_url

    def search(self, target):
        branchs = self.search_branch(target)
        has_branch = False

        for branch in branchs:
            has_branch = True
            yield branch

        if has_branch:
            return

        # gitee的搜索 搜了个稀烂 匹配到的无关的太多
        url = f"https://gitee.com/api/v5/search/repositories"
        params = {
            'access_token': self.access_token,
            'owner': self.owner,
            'q': target,
            'page': 1,
            'per_page': 20,
        }

        r = requests.get(url, params=params)
        if not r.status_code == 200:
            return

        # 整理结果
        for repo in json.loads(r.text):
            yield repo['name'], self.owner, 'gitee', repo['name'], repo['html_url']

